/*
 * Copyright 2009-2015 by WWW.KNET.CN  All rights reserved.
 */

package cn.knet.sp.ncrm.modules.sys.utils;

import cn.knet.sp.ncrm.modules.sys.customerstatus.entity.CustomerStatus;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


//import cn.knet.agent.domain.UserAccount;
//import cn.knet.agent.webservice.CommonUserService;
import cn.knet.sp.ncrm.common.config.Global;
import cn.knet.sp.ncrm.common.service.BaseService;
import cn.knet.sp.ncrm.common.utils.CacheUtils;
import cn.knet.sp.ncrm.common.utils.SpringContextHolder;
import cn.knet.sp.ncrm.modules.sys.area.dao.AreaDao;
import cn.knet.sp.ncrm.modules.sys.menu.dao.MenuDao;
import cn.knet.sp.ncrm.modules.sys.office.dao.OfficeDao;
import cn.knet.sp.ncrm.modules.sys.role.dao.RoleDao;
import cn.knet.sp.ncrm.modules.sys.user.dao.UserDao;
import cn.knet.sp.ncrm.modules.sys.area.entity.Area;
import cn.knet.sp.ncrm.modules.sys.menu.entity.Menu;
import cn.knet.sp.ncrm.modules.sys.office.entity.Office;
import cn.knet.sp.ncrm.modules.sys.role.entity.Role;
import cn.knet.sp.ncrm.modules.sys.user.entity.User;
import cn.knet.sp.ncrm.modules.sys.security.SystemAuthorizingRealm;
//import cn.knet.sp.ncrm.modules.sys.security.cas.SystemCasAuthorizingRealm;

/**
 * 用户工具类
 *
 * @author ThinkGem
 * @version 2013-12-05
 */
public class UserUtils {

	private static UserDao userDao = SpringContextHolder.getBean(UserDao.class);
	private static RoleDao roleDao = SpringContextHolder.getBean(RoleDao.class);
	private static MenuDao menuDao = SpringContextHolder.getBean(MenuDao.class);
	private static AreaDao areaDao = SpringContextHolder.getBean(AreaDao.class);
	private static OfficeDao officeDao = SpringContextHolder.getBean(OfficeDao.class);

//	private static CommonUserService commonUserService = SpringContextHolder.getBean(CommonUserService.class);

	public static final String USER_CACHE = "userCache";
	public static final String USER_LIST_CACHE = "userListCache";
	public static final String USER_CACHE_ID_ = "id_";
	public static final String USER_CACHE_LOGIN_NAME_ = "ln";
	public static final String USER_CACHE_LIST_BY_OFFICE_ID_ = "oid_";

	public static final String CACHE_ROLE_LIST = "roleList";
	public static final String CACHE_MENU_LIST = "menuList";
	public static final String CACHE_AREA_LIST = "areaList";
	public static final String CACHE_OFFICE_LIST = "officeList";
	public static final String CACHE_OFFICE_ALL_LIST = "officeAllList";

	/**
	 * 根据ID获取用户
	 *
	 * @return 取不到返回null
	 */
	public static User get(String id) {
		User user = (User) CacheUtils.get(USER_CACHE, USER_CACHE_ID_ + id);
		if (user == null) {
			user = userDao.get(id);
			if (user == null) {
				return null;
			}
			user.setRoleList(roleDao.findList(new Role(user)));
			CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
			CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
		}
		return user;
	}

	public static User getByLoginName(String loginName,boolean flashCache) {
		if(flashCache){
			clearCache();
		}
		return getByLoginName(loginName);
	}
		/**
		 * 根据登录名获取用户
		 *
		 * @return 取不到返回null
		 */
	public static User getByLoginName(String loginName) {
		User user = (User) CacheUtils.get(USER_CACHE, USER_CACHE_LOGIN_NAME_ + loginName);
		if (user == null) {
			user = userDao.getByLoginName(new User(null, loginName));
			if (user == null) {
				return null;
			}
			user.setRoleList(roleDao.findList(new Role(user)));
			CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
			CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
		}
		return user;
	}

	public static User getByNo(String no) {
		User u = new User();
		u.setNo(no);
		User user = userDao.getByEntity(u);
		if (user == null) {
			return null;
		}
		return user;
	}

	/**
	 * 清除当前用户缓存
	 */
	public static void clearCache() {
		removeCache(CACHE_ROLE_LIST);
		removeCache(CACHE_MENU_LIST);
		removeCache(CACHE_AREA_LIST);
		removeCache(CACHE_OFFICE_LIST);
		removeCache(CACHE_OFFICE_ALL_LIST);
		UserUtils.clearCache(getUser());
		//Cache cache =CacheUtils.getCacheManager().getCache(USER_CACHE);
		//cache.removeAll();
	}

	/**
	 * 清除指定用户缓存
	 */
	public static void clearCache(User user) {
		CacheUtils.remove(USER_CACHE, USER_CACHE_ID_ + user.getId());
		CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName());
		CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getOldLoginName());
		if (user.getOffice() != null && user.getOffice().getId() != null) {
			CacheUtils.remove(USER_CACHE, USER_CACHE_LIST_BY_OFFICE_ID_ + user.getOffice().getId());
		}
	}

	/**
	 * 获取所有用户列表
	 *
	 * @return 取不到返回 new ArrayList<>()
	 */
	public static List<User> listUser() {
		List<User> userList = (List<User>) CacheUtils.get(USER_LIST_CACHE, USER_LIST_CACHE);
		if (null==userList) {
			User entity = new User();
			entity.setDelFlag("0");
			userList = userDao.findAllList(entity);
			if (null==userList) {
				return new ArrayList<>();
			}
			CacheUtils.put(USER_LIST_CACHE, USER_LIST_CACHE, userList);
		}
		return userList;
	}

	/**
	 * 获取当前用户
	 *
	 * @return 取不到返回 new User()
	 */
	public static User getUser() {
		SystemAuthorizingRealm.Principal principal = getSysPrincipal();
		if (principal != null) {
			User user = getByLoginName(principal.getLoginName());
			if (user != null) {
				return user;
			}
			return new User();
		}
		// 如果没有登录，则返回实例化空的User对象。
		return new User();
	}

	/**
	 * 获取当前用户角色列表
	 */
	public static List<Role> getRoleList() {
		@SuppressWarnings("unchecked")
		List<Role> roleList = (List<Role>) getCache(CACHE_ROLE_LIST);
		if (roleList == null) {
			User user = getUser();
			if (user.isAdmin()) {
				roleList = roleDao.findAllList(new Role());
			} else {
				Role role = new Role();
				role.getSqlMap().put("dsf", BaseService.dataScopeFilter(user.getCurrentUser(), "o", "u"));
				roleList = roleDao.findList(role);
			}
			//putCache(CACHE_ROLE_LIST, roleList);
		}
		return roleList;
	}

	/**
	 * 获取当前用户授权菜单
	 */
	public static List<Menu> getMenuList() {
		@SuppressWarnings("unchecked")
		List<Menu> menuList = (List<Menu>) getCache(CACHE_MENU_LIST);
		if (menuList == null) {
			User user = getUser();
			if (user.isAdmin()) {
				menuList = menuDao.findAllList(new Menu());
			} else {
				Menu m = new Menu();
				m.setUserId(user.getId());
				menuList = menuDao.findByUserId(m);
			}
			putCache(CACHE_MENU_LIST, menuList);
		}
		return menuList;
	}

	/**
	 * 获取当前用户授权的区域
	 */
	public static List<Area> getAreaList() {
		@SuppressWarnings("unchecked")
		List<Area> areaList = (List<Area>) getCache(CACHE_AREA_LIST);
		if (areaList == null) {
			areaList = areaDao.findAllList(new Area());
			putCache(CACHE_AREA_LIST, areaList);
		}
		return areaList;
	}

	/**
	 * 获取当前用户有权限访问的部门
	 */
	public static List<Office> getOfficeList() {
		@SuppressWarnings("unchecked")
		List<Office> officeList = (List<Office>) getCache(CACHE_OFFICE_LIST);
		if (officeList == null) {
			User user = getUser();
			if (user.isAdmin()) {
				officeList = officeDao.findAllList(new Office());
			} else {
				Office office = new Office();
				office.getSqlMap().put("dsf", BaseService.dataScopeFilter(user, "a", ""));
				officeList = officeDao.findList(office);
			}
			putCache(CACHE_OFFICE_LIST, officeList);
		}
		return officeList;
	}

	/**
	 * 获取当前用户有权限访问的部门
	 */
	public static List<Office> getOfficeAllList() {
		@SuppressWarnings("unchecked")
		List<Office> officeList = (List<Office>) getCache(CACHE_OFFICE_ALL_LIST);
		if (officeList == null) {
			officeList = officeDao.findAllList(new Office());
		}
		return officeList;
	}

	/**
	 * 获取授权主要对象
	 */
	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}

//	/**
//	 * 获取当前登录者对象
//	 */
//	public static SystemCasAuthorizingRealm.Principal getPrincipal() {
//		try {
//			Subject subject = SecurityUtils.getSubject();
//			SystemCasAuthorizingRealm.Principal
//					principal =
//					(SystemCasAuthorizingRealm.Principal) subject.getPrincipal();
//			if (principal != null) {
//				return principal;
//			}
////			subject.logout();
//		} catch (UnavailableSecurityManagerException e) {
//
//		} catch (InvalidSessionException e) {
//
//		}
//		return null;
//	}
	/**
	 * add by jief
	 * 获取当前登录者对象
	 */
	public static SystemAuthorizingRealm.Principal getSysPrincipal() {
		try {
			Subject subject = SecurityUtils.getSubject();
			SystemAuthorizingRealm.Principal
					principal =
					(SystemAuthorizingRealm.Principal) subject.getPrincipal();
			if (principal != null) {
				return principal;
			}
//			subject.logout();
		} catch (UnavailableSecurityManagerException e) {

		} catch (InvalidSessionException e) {

		}
		return null;
	}
	public static Session getSession() {
		try {
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession(false);
			if (session == null) {
				session = subject.getSession();
			}
			if (session != null) {
				return session;
			}
//			subject.logout();
		} catch (InvalidSessionException e) {

		}
		return null;
	}

	// ============== User Cache ==============

	public static Object getCache(String key) {
		return getCache(key, null);
	}

	public static Object getCache(String key, Object defaultValue) {
//		Object obj = getCacheMap().get(key);
		Object obj = getSession().getAttribute(key);
		return obj == null ? defaultValue : obj;
	}

	public static void putCache(String key, Object value) {
//		getCacheMap().put(key, value);
		getSession().setAttribute(key, value);
	}

	public static void removeCache(String key) {
//		getCacheMap().remove(key);
		getSession().removeAttribute(key);
	}

//	public static Map<String, Object> getCacheMap(){
//		Principal principal = getPrincipal();
//		if(principal!=null){
//			return principal.getCacheMap();
//		}
//		return new HashMap<String, Object>();
//	}


	public static String saveUserAccount(User user) throws Exception {
//		if(user.getNewPassword() == null || user.getNewPassword().equals("")) {
//			user.setNewPassword("abc123");
//		}
//		//添加用户
//		UserAccount newuserAccount = new UserAccount();
//		newuserAccount.setUsername(user.getLoginName());
//		newuserAccount.setEmail(user.getEmail());
//		newuserAccount.setPassword(CrmCommonUtils.PasswordEncode(user.getNewPassword()));
//		newuserAccount.setName(user.getName());
//		newuserAccount.setCreatedDt(new Date());
//		newuserAccount.setLastUpdatedDt(new Date());
//		newuserAccount.setVersion(1);
//		newuserAccount.setEmail(user.getEmail().equals("") ? "crm@knet.cn" : user.getEmail());
//		newuserAccount.setLocked(user.getLoginFlag().equals("yes") ? true : false);
//		newuserAccount.setDataPermissionType("ALL_DATA");
//		newuserAccount.setIsManager(0);
//
//		String id = commonUserService.createUserAccount(newuserAccount);
//		//添加或移除角色
//		saveNcrmRole(user.getLoginName(),user.getLoginFlag());
//		return id;
		return null;
	}

	public static void saveNcrmRole(String loginName,String loginFlag) throws Exception {
		//添加角色
//		if(loginFlag.equals("1")) {
//			commonUserService.addUserRole(loginName, Global.getConfig("ncrm.role"), Global.getConfig("app.systemTag"));
//		} else {
//			commonUserService.removeUserRole(loginName, Global.getConfig("ncrm.role"), Global.getConfig("app.systemTag"));
//		}
	}

	public static boolean isKnetUser(String loginName) throws Exception {
//		UserAccount userAccount = commonUserService.getUserAccount(loginName);
//		if (userAccount != null) {
//			return true;
//		}
		return false;
	}

	public static void removeNcrmRole(String loginName) throws Exception {
		//移除角色
//		commonUserService.removeUserRole(loginName, Global.getConfig("ncrm.role"), Global.getConfig("app.systemTag"));
	}


//	public static UserAccount getUserAccount(String loginName) throws Exception {
//		//添加角色
//		UserAccount userAccount = commonUserService.getUserAccount(loginName);
//		return userAccount;
//	}


}
